﻿using IOP.OpenType.Tables;
using IOP.OpenType;
using System;
using System.Buffers;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Threading.Tasks;

namespace IOP.Codec.OpenType
{
    /// <summary>
    /// 最大配置文件加载器
    /// </summary>
    public class MaxpTableLoader
    {
        /// <summary>
        /// 加载
        /// </summary>
        /// <param name="stream"></param>
        /// <param name="entry"></param>
        /// <returns></returns>
        public async Task<MaxpTable> Load(FileStream stream, TableEntry entry)
        {
            uint offset = entry.Offset;
            uint length = entry.Length;
            stream.Seek(offset, SeekOrigin.Begin);
            Memory<byte> bytes = new byte[length];
            await stream.ReadAsync(bytes);
            var table = ReadMaxp(bytes);
            table.Entry = entry;
            return table;
        }

        private MaxpTable ReadMaxp(Memory<byte> data)
        {
            ReadOnlySequence<byte> sequence = new ReadOnlySequence<byte>(data);
            SequenceReader<byte> reader = new SequenceReader<byte>(sequence);
            MaxpTable maxp = new MaxpTable();
            reader.TryReadBigEndian(out int v);
            reader.TryReadBigEndian(out short n);
            maxp.Version = v;
            maxp.NumGlyphs = (ushort)n;
            if (maxp.Version < 1.0) return maxp;
            else
            {
                reader.TryReadBigEndian(out short maxP);
                reader.TryReadBigEndian(out short maxCounts);
                reader.TryReadBigEndian(out short maxCPoints);
                reader.TryReadBigEndian(out short maxComContours);
                reader.TryReadBigEndian(out short maxZones);
                reader.TryReadBigEndian(out short maxTwP);
                reader.TryReadBigEndian(out short maxStorage);
                reader.TryReadBigEndian(out short maxFunc);
                reader.TryReadBigEndian(out short maxStack);
                reader.TryReadBigEndian(out short maxSize);
                reader.TryReadBigEndian(out short maxComponent);
                reader.TryReadBigEndian(out short maxCDepth);
                maxp.MaxPoints = (ushort)maxP;
                maxp.MaxContours = (ushort)maxCounts;
                maxp.MaxCompositePoints = (ushort)maxCPoints;
                maxp.MaxCompositeContours = (ushort)maxComContours;
                maxp.MaxZones = (ushort)maxZones;
                maxp.MaxTwilightPoints = (ushort)maxTwP;
                maxp.MaxStorage = (ushort)maxStorage;
                maxp.MaxFunctionDefs = (ushort)maxFunc;
                maxp.MaxStackElements = (ushort)maxStack;
                maxp.MaxSizeOfInstructions = (ushort)maxSize;
                maxp.MaxComponentElements = (ushort)maxComponent;
                maxp.MaxComponentDepth = (ushort)maxCDepth;
                return maxp;
            }
        }
    }
}
